package whu.cn.whushare.ui.main.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.androidplus.util.ViewMapping;
import com.androidplus.util.ViewMappingUtil;
import com.dd.processbutton.iml.ActionProcessButton;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import whu.cn.whushare.R;
import whu.cn.whushare.bean.User;
import whu.cn.whushare.common.Constants;
import whu.cn.whushare.net.DownloadParams;
import whu.cn.whushare.net.Downloader;
import whu.cn.whushare.ui.common.BaseActivity;
import whu.cn.whushare.ui.common.LoadingHelper;
import whu.cn.whushare.ui.main.MainTabActivity;
import whu.cn.whushare.ui.main.activity.adapter.SignUserListAdapter;
import whu.cn.whushare.ui.main.activity.bean.Activity;
import whu.cn.whushare.ui.main.activity.bean.ActivityDetail;
import whu.cn.whushare.ui.main.known.AddAnswerActivity;
import whu.cn.whushare.ui.main.known.AnswerDetailActivity;
import whu.cn.whushare.ui.main.known.QuestionDetailActivity;
import whu.cn.whushare.ui.main.known.adapter.AnswerListAdapter;
import whu.cn.whushare.ui.main.known.adapter.TopicAdapter;
import whu.cn.whushare.ui.main.known.bean.AllQuestion;
import whu.cn.whushare.ui.main.known.bean.AnswerWrapBean;
import whu.cn.whushare.ui.main.known.bean.FavorBean;
import whu.cn.whushare.ui.main.known.bean.QuestionDetail;
import whu.cn.whushare.ui.main.known.bean.Topic;
import whu.cn.whushare.ui.main.my.LoginActivity;
import whu.cn.whushare.ui.main.my.RegisterActivity;
import whu.cn.whushare.util.SetOnClickUtil;
import whu.cn.whushare.util.Utils;

/**
 * Created by xiaoping on 2015/3/26.
 */
@ViewMapping(id=R.layout.activity_activity_detail)
public class ActivityDetailActivity extends BaseActivity implements View.OnClickListener{
    @ViewMapping(id = R.id.activity)
    private TextView mActivity;
    @ViewMapping(id = R.id.activity_place)
    private TextView mActivityPlace;
    @ViewMapping(id = R.id.end_time)
    private TextView mEndTime;
    @ViewMapping(id = R.id.show_time)
    private TextView mShowTime;
    @ViewMapping(id = R.id.activity_content)
    private TextView mActivityContent;
    @ViewMapping(id = R.id.sign_count)
    private TextView mSignCount;
    @ViewMapping(id = R.id.contact)
    private TextView mContact;
    @ViewMapping(id = R.id.contact_mean)
    private TextView mContactMean;
    @ViewMapping(id = R.id.main_content)
    private RelativeLayout mMainLayout;
    @ViewMapping(id = R.id.sign_user_list)
    private PullToRefreshListView mSignUserListView;
    private LoadingHelper mLoadingHelper;
    private LoadingHelper mSignUserLoadingHelper;
    private String mActivityId;
    private SignUserListAdapter adapter;
    private List<User> mSignUser= new ArrayList<>();
    private boolean isSign;
    private boolean mHasInited;
    private boolean mHasSignUserListInited;
    private  Spanned sp;
    private String activityName;
    private String activityContent;
    private String html2="<p>";
    public static Intent getStartIntent(Context context, String activityID) {
        Intent i = new Intent(context, ActivityDetailActivity.class);
        i.putExtra("activity_id", activityID);
        return i;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getIntentData();
        initView();
        getActivityDetail();
        initActions();
    }

    private void getIntentData() {
        if (getIntent() != null) {
            mActivityId = getIntent().getStringExtra("activity_id");
        }
    }

    private void initView() {
        View root = ViewMappingUtil.mapView(this, this);
        SetOnClickUtil.registerOnClick(this);
        getTopBar(root);
        mTopBar.title.setText("活动详情");
        mTopBar.rightText.setVisibility(View.VISIBLE);
        mTopBar.rightText.setText("报名");
        mTopBar.searchLayout.setVisibility(View.GONE);
        mTopBar.rightText.setMode(ActionProcessButton.Mode.ENDLESS);
        initLoadingHelper();

        initSignUserListView();
    }

    private void initSignUserListView() {

        mSignUserListView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        mSignUserListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (mSignUser.size() >= mTotal) {
                    Utils.setRefreshLabelToLast(ActivityDetailActivity.this, mSignUserListView);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mSignUserListView.onRefreshComplete();
                        }
                    }, 500);
                } else {
                    getSignUserList();
                }
            }
        });

    }

    private void initLoadingHelper() {
        mLoadingHelper = new LoadingHelper(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivityDetail();

            }
        });
        mLoadingHelper.onCreateView(LayoutInflater.from(this), mMainLayout);
        mSignUserLoadingHelper = new LoadingHelper(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getSignUserList();
            }
        });
        mSignUserLoadingHelper.onCreateView(LayoutInflater.from(this), mSignUserListView);
    }

    private void getActivityDetail() {
        mLoadingHelper.showLoadingView(mHasInited);
        Downloader.getInstance(this).getActivityDetail(mActivityId, this, null);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> void onSuccess(DownloadParams.PARSING_TYPE type, T response, Object obj) {
        super.onSuccess(type, response, obj);
        switch (type) {
            case ACTIVITY_DETAIL:
                mHasInited = true;
                ActivityDetail activityDetail = (ActivityDetail) response;
                updateActivityDetail(activityDetail);
                mLoadingHelper.showContentView();
                getSignUserList();
                break;
            case SIGN_USER_LIST:
                mHasSignUserListInited= true;
                mSignUserLoadingHelper.showContentView();
                List<User> signUserList = (List<User>) response;
                updateSignUserList(signUserList);
                break;
            case SIGN:
                FavorBean favorBean = (FavorBean) response;
                isSign= favorBean.type.equals("add");
                processBtnEnd();


               startActivity(ActivityDetailActivity.getStartIntent(ActivityDetailActivity.this,mActivityId));
               toast(msg);

                break;
            default:
                break;
        }
    }

    private void updateActivityDetail(ActivityDetail activityDetail) {
        activityName=activityDetail.getActivity().getActivityName();
        mActivity.setText(activityDetail.getActivity().getActivityName());
        mActivityPlace.setText("活动地点："+activityDetail.getActivity().getAddress());
        //  mEndTime.setText("截止日期："+activityDetail.getActivity().getEndTime());
        activityContent=activityDetail.getActivity().getActivityDetail();

       String html= activityDetail.getActivity().getActivityDetail()+"";
        if(html!=""&&html.length()>3) {
            if (html.substring(0, 3).equals("<p>"))
            {
                String[] html1 = html.split(">");
                for (int i = 1; i < html1.length; i++) {
                    html2 = html2 + html1[i] + ">" + "<br>";
                }
            }
            else
                html2=html;
        }
        else
        {

            html2 = html;

        }


        final String html3=html2;
        new AsyncTask<String,String,Spanned>(){
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(Spanned s) {
                super.onPostExecute(s);

                mActivityContent.setText(s);
            }

            @Override
            protected Spanned doInBackground(String... params) {

                sp = Html.fromHtml(html3,
                        new Html.ImageGetter() {
                            @Override
                            public Drawable getDrawable(String source) {
                                source = "http://www.027team.com" + source;
                                InputStream is = null;
                                try {
                                    is = new URL(source).openStream();
                                    Drawable d = Drawable.createFromStream(is, "src");

                                    d.setBounds(0,0, d.getIntrinsicWidth()*3, d.getIntrinsicHeight()*3);
                                    is.close();
                                    return d;
                                } catch (Exception e) {
                                    return null;
                                }
                            }
                        }, null);
                return sp;
            }
        }.execute();


        mShowTime.setText("举办时间："+activityDetail.getActivity().getHostTime());
      //  mActivityContent.setText(activityDetail.getActivity().getActivityDetail());
        mContact .setText("举办方：" + activityDetail.getActivity().getHostPeople());
        mContactMean.setText("联系方式：" + activityDetail.getActivity().getPhoneNum());
        mSignCount.setText(String.format(getString(R.string.sign_count),activityDetail.getSignNum()));
    }

    private void getSignUserList() {
        mSignUserLoadingHelper.showLoadingView(mHasSignUserListInited);
        Downloader.getInstance(this).getSignUserList(mActivityId, this,mActivityId);
    }

    private void updateSignUserList(List<User> signUserList) {
        if (signUserList != null && signUserList.size() > 0) {
            mSignUser.clear();
            mSignUser.addAll(signUserList);
            adapter = new SignUserListAdapter(this,mSignUser);
            mSignUserListView.setAdapter(adapter);
        }
    }

    @Override
    public void onFail(DownloadParams.PARSING_TYPE type, VolleyError error) {
        super.onFail(type, error);
        switch (type) {
            case ACTIVITY_DETAIL:
                if (!mHasInited) {
                    mLoadingHelper.showRetryView();
                }
                break;
            case SIGN_USER_LIST:
                if (!mHasSignUserListInited) {
                    mSignUserLoadingHelper.showRetryView();
                }
                mSignUserListView.onRefreshComplete();
                break;
            case SIGN:
                if (TextUtils.isEmpty(msg)) {
                    toast(isSign ? "取消报名失败" : "报名失败");
                } else {
                    toast(msg);
                }
                processBtnEnd();
                break;

            default:
                break;
        }
    }
    private void initActions() {
        mTopBar.rightText.setOnClickListener(this);
        mActivityContent.setOnClickListener(this);

    }
    private void processBtnEnd() {
        mTopBar.rightText.setProgress(100);
        mTopBar.rightText.setText(isSign ? "报名" :"取消报名");
        mTopBar.rightText.setEnabled(true);
    }
    @Override
    public void onClick(View v){
       switch (v.getId()){
           case R.id.top_right_txt:
               mTopBar.rightText.setEnabled(false);
               requestSignActivity();
               break;
           case R.id.activity_content:
               startActivityForResult(ActivityShow.getStartIntent(ActivityDetailActivity.this,activityContent,activityName),1);
           default:
               break;
       }

    }
    private void requestSignActivity() {
        Downloader.getInstance(this).requestSign(mActivityId, this);
        mTopBar.rightText.setProgress(50);
    }

}